package com.ls.lserp.modules.produce.web;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.ls.lserp.common.utils.CacheUtils;
import com.ls.lserp.common.utils.MacUtils;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.order.entity.Order;
import com.ls.lserp.modules.order.entity.StyleOptionEntity;
import com.ls.lserp.modules.produce.entity.CustomizationQualityEntity;
import com.ls.lserp.modules.produce.service.CustomizationQualityService;
import com.ls.lserp.modules.sys.entity.DesignoptionCache;
import com.ls.lserp.modules.sys.utils.UserUtils;

import freemarker.template.Configuration;
import groovy.util.ResourceException;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping(value = "${adminPath}/customization/quality/")
public class CustomizationQualityController extends BaseController {
	
	public static final String CACHE_QUALITY_VALUE_MAP_34 = "qualityValueMap34";
	public static final String CACHE_QUALITY_VALUE_MAP_35 = "qualityValueMap35";
	public static final String CACHE_QUALITY_VALUE_MAP_36 = "qualityValueMap36";
	public static final String CACHE_QUALITY_VALUE_MAP_37 = "qualityValueMap37";
	
	@Autowired
	private CustomizationQualityService customizationQualityService;
	@Autowired
	Configuration freemarkerConfiguration;
	@ModelAttribute
	public CustomizationQualityEntity get(@RequestParam(required=false) String id) {
		// 判断id是否为空
		if (StringUtils.isNotBlank(id)){
			// 执行查询语句 查询基本信息
			return customizationQualityService.get(Long.parseLong(id));
		}else{
			// 若为空，实例化
			return new CustomizationQualityEntity();
		}
	}
	/**
	 * 定制订单质检(订单查询)
	 * @param request
	 * @param model
	 * @return
	 */
	@RequiresPermissions("customization:quality:view")
	@RequestMapping(value = { "" })
	public String customizationEnter(String operatingId,HttpServletRequest request,Model model) throws Exception{
		/*// 获取用户IP
		String strIp = MacUtils.getIpAddr(request);
		// 根据IP获取工位号
		String operatingId = customizationQualityService.selectOperatingId(strIp);*/
		//putQualityCache(operatingId);
		/*model.addAttribute("operatingId",operatingId);
		if (operatingId != null) {
			return "modules/produce/CustomizationQualityEnter";
		} else {
			return "modules/produce/PermissionCommen";
		}*/
		model.addAttribute("operatingId",operatingId);
		model.addAttribute("user",UserUtils.getUser().getFirstName()+UserUtils.getUser().getLastName());
		return "modules/produce/CustomizationQualityEnter";
	}
	/**
	 * 定制订单质检(订单查询)
	 * @param request
	 * @param model
	 * @return
	 */
	@RequiresPermissions("customization:quality:view")
	@RequestMapping(value = { "buttonEnter" })
	public String customizationButtonEnter(String operatingId,HttpServletRequest request,Model model) throws Exception{
		model.addAttribute("operatingId",operatingId);
		model.addAttribute("user", UserUtils.getUser());
		return "modules/produce/CustomizationQualityButtonEnter";
	}
	/**
	 * @Title: putQualityCache
	 * @Description: 质检项目全量放入缓存
	 * @author 于辉
	 *
	 */
	@SuppressWarnings("unchecked")
	public void putQualityCache(String operatingId) {
		if ("34".equals(operatingId)) {
			Map<String, List<Order>> qualityMap34 = (Map<String, List<Order>>) CacheUtils.get(CACHE_QUALITY_VALUE_MAP_34);
			if (qualityMap34 == null) {
				qualityMap34 = Maps.newHashMap();
				for (Order order : customizationQualityService.findAllList(new Order(),34L)) {
					List<Order> dictList = qualityMap34.get(order.getStyleBarCode());
					if (dictList != null) {
						dictList.add(order);
						qualityMap34.put(order.getStyleBarCode(),  Lists.newArrayList(dictList));
					} else {
						qualityMap34.put(order.getStyleBarCode(), Lists.newArrayList(order));
					}
					
				}
				CacheUtils.put(CACHE_QUALITY_VALUE_MAP_34, qualityMap34);
			}
		}else if ("35".equals(operatingId)) {
			Map<String, List<Order>> qualityMap35 = (Map<String, List<Order>>) CacheUtils.get(CACHE_QUALITY_VALUE_MAP_35);
			if (qualityMap35 == null) {
				qualityMap35 = Maps.newHashMap();
				for (Order order : customizationQualityService.findAllList(new Order(),35L)) {
					List<Order> dictList = qualityMap35.get(order.getStyleBarCode());
					if (dictList != null) {
						dictList.add(order);
						qualityMap35.put(order.getStyleBarCode(),  Lists.newArrayList(dictList));
					} else {
						qualityMap35.put(order.getStyleBarCode(), Lists.newArrayList(order));
					}
					
				}
				CacheUtils.put(CACHE_QUALITY_VALUE_MAP_35, qualityMap35);
			}
		}else if ("36".equals(operatingId)) {
			Map<String, List<Order>> qualityMap36 = (Map<String, List<Order>>) CacheUtils.get(CACHE_QUALITY_VALUE_MAP_36);
			if (qualityMap36 == null) {
				qualityMap36 = Maps.newHashMap();
				for (Order order : customizationQualityService.findAllList(new Order(),36L)) {
					List<Order> dictList = qualityMap36.get(order.getStyleBarCode());
					if (dictList != null) {
						dictList.add(order);
						qualityMap36.put(order.getStyleBarCode(),  Lists.newArrayList(dictList));
					} else {
						qualityMap36.put(order.getStyleBarCode(), Lists.newArrayList(order));
					}
					
				}
				CacheUtils.put(CACHE_QUALITY_VALUE_MAP_36, qualityMap36);
			}
		}else if ("37".equals(operatingId)) {
			Map<String, List<Order>> qualityMap37 = (Map<String, List<Order>>) CacheUtils.get(CACHE_QUALITY_VALUE_MAP_37);
			if (qualityMap37 == null) {
				qualityMap37 = Maps.newHashMap();
				for (Order order : customizationQualityService.findAllList(new Order(),37L)) {
					List<Order> dictList = qualityMap37.get(order.getStyleBarCode());
					if (dictList != null) {
						dictList.add(order);
						qualityMap37.put(order.getStyleBarCode(),  Lists.newArrayList(dictList));
					} else {
						qualityMap37.put(order.getStyleBarCode(), Lists.newArrayList(order));
					}
					
				}
				CacheUtils.put(CACHE_QUALITY_VALUE_MAP_37, qualityMap37);
			}
		}else{
			
		}
	}
    /**
     * 定制订单质检(订单检测详细)
     *
     *
     * @return
     */
	@SuppressWarnings("unchecked")
	@RequiresPermissions("customization:quality:view")
    @RequestMapping(value = { "searchList" })
    public String searchList(CustomizationQualityEntity customizationQualityEntity,Model model) {
		/*Map<String, List<Order>> qualityValueMap;
		String keyOfMap = "";
		if ("34".equals(customizationQualityEntity.getItemId ())) {
			keyOfMap = CACHE_QUALITY_VALUE_MAP_34;
		}else if ("35".equals(customizationQualityEntity.getItemId ())) {
			keyOfMap = CACHE_QUALITY_VALUE_MAP_35;
		}else if ("36".equals(customizationQualityEntity.getItemId ())) {
			keyOfMap = CACHE_QUALITY_VALUE_MAP_36;
		}else if ("37".equals(customizationQualityEntity.getItemId ())) {
			keyOfMap = CACHE_QUALITY_VALUE_MAP_37;
		}
		qualityValueMap = 	(Map<String, List<Order>>) CacheUtils.get(keyOfMap);
		if (qualityValueMap == null) {

			qualityValueMap = Maps.newHashMap();
			for (Order orz :  customizationQualityService.findAllList(new Order(),Long.parseLong(customizationQualityEntity.getItemId ()))) {
				qualityValueMap.put(orz.getStyleBarCode(), Lists.newArrayList(orz));
			}
			CacheUtils.put(keyOfMap, qualityValueMap);

		}
		List<Order> returnOrders = qualityValueMap.get(customizationQualityEntity.getBarCode ());
		Order returnOrder = returnOrders.get(0);
		if ("36".equals(customizationQualityEntity.getItemId ())) {
			Order orz = customizationQualityService.getDataOfFit01(returnOrder.getStyleNo());
			returnOrder.setWashControl(orz.getWashControl());
			returnOrder.setSfpControl(orz.getSfpControl());
			returnOrder.setSbdControl(orz.getSbdControl());
		}
		model.addAttribute("orderInfo",returnOrder);
		model.addAttribute("styleQualityList",returnOrder.getStyleOpList());*/
		try {
			Order orderInfo;
			orderInfo = customizationQualityService.getOrderInfo(customizationQualityEntity.getOrderCd(),customizationQualityEntity.getItemId ());
			orderInfo.preInsert();
			model.addAttribute("orderInfo",orderInfo);
			model.addAttribute("styleQualityList",orderInfo.getStyleOpList());
			model.addAttribute("itemId",customizationQualityEntity.getItemId ());
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		// 尺寸检查01,02
		if("36".equals (customizationQualityEntity.getItemId ()) || "37".equals (customizationQualityEntity.getItemId ())) {
			return "modules/produce/CustomizationFitQualityDetailed";
			// 整烫前,整烫后
		} else if ("34".equals (customizationQualityEntity.getItemId ()) || "35".equals (customizationQualityEntity.getItemId ())){
			return "modules/produce/CustomizationQualityDetailed";
		} else {
			return "modules/produce/PermissionCommen";
		}
    }
    
    /**
	 *保存信息
	 * 
	 * @return
	 * @throws ParseException
	 * @throws ResourceException
	 */
	@RequiresPermissions("customization:quality:edit")
	@RequestMapping(value = "saveData")
	@ResponseBody
	public String saveData(StyleOptionEntity styleOptionEntity, HttpServletResponse response) throws ResourceException {
		// 临时变量
        String returnFLg = "";
        try {
			// 保存数据
            String changeFLg = customizationQualityService.updateQcCheck(styleOptionEntity);
			// 全是待检测状态
            if ("noChange".equals (changeFLg)) {
                returnFLg = changeFLg;
			// 全部通过状态
            } else if ("changeAll_OK".equals (changeFLg)) {
                returnFLg = "OK";
			// 其他
            } else {
				returnFLg = "change_Fail";
			}
        }catch (Exception e) {
        	// 打印log
        	logger.error(e.getMessage(),e);
            // 保存失败返回提示信息
            return renderString(response, "NG");
        }
        // 保存成功返回提示信息
        return renderString(response, returnFLg);
    }

    /**
     *保存信息
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("customization:quality:edit")
    @RequestMapping(value = "saveFitData")
    @ResponseBody
    public String saveFitData(StyleOptionEntity styleOptionEntity, HttpServletResponse response) throws ResourceException {
        // 保存数据
        customizationQualityService.updateFitQcCheck(styleOptionEntity);
        //updateFitCache(styleOptionEntity);
        // 保存成功返回提示信息
        return renderString(response, "");
    }
    
    /**
     * 更新质检Fit缓存
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @ResponseBody
    public void updateFitCache(StyleOptionEntity styleOptionEntity) throws ResourceException {
    	Map<String, List<Order>> qualityValueMap;
		String keyOfMap = "";
		if ("34".equals(styleOptionEntity.getItemId ())) {
			keyOfMap = CACHE_QUALITY_VALUE_MAP_34;
		}else if ("35".equals(styleOptionEntity.getItemId ())) {
			keyOfMap = CACHE_QUALITY_VALUE_MAP_35;
		}else if ("36".equals(styleOptionEntity.getItemId ())) {
			keyOfMap = CACHE_QUALITY_VALUE_MAP_36;
		}else if ("37".equals(styleOptionEntity.getItemId ())) {
			keyOfMap = CACHE_QUALITY_VALUE_MAP_37;
		}
		qualityValueMap = 	(Map<String, List<Order>>) CacheUtils.get(keyOfMap);
		List<Order> returnOrders = qualityValueMap.get(styleOptionEntity.getStyleBarCode());
		Order returnOrder = returnOrders.get(0);
		for (StyleOptionEntity sEntity:returnOrder.getStyleOpList()) {
			if ((sEntity.getItemCode()+"-"+sEntity.getItemValue()).equals(styleOptionEntity.getItemCode()+"-"+styleOptionEntity.getItemValue())) {
				sEntity.setQcCheck(styleOptionEntity.getQcCheck());
				sEntity.setFitValue(styleOptionEntity.getFitValue());
			}
		}
		qualityValueMap.put(styleOptionEntity.getStyleBarCode(), Lists.newArrayList(returnOrder));
		CacheUtils.put(keyOfMap, qualityValueMap);
    }
     
    /**
     * 更新质检整烫缓存
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @ResponseBody
    public void updateCache(StyleOptionEntity styleOptionEntity) throws ResourceException {
    	Map<String, List<Order>> qualityValueMap;
		String keyOfMap = "";
		if ("34".equals(styleOptionEntity.getItemId ())) {
			keyOfMap = CACHE_QUALITY_VALUE_MAP_34;
		}else if ("35".equals(styleOptionEntity.getItemId ())) {
			keyOfMap = CACHE_QUALITY_VALUE_MAP_35;
		}else if ("36".equals(styleOptionEntity.getItemId ())) {
			keyOfMap = CACHE_QUALITY_VALUE_MAP_36;
		}else if ("37".equals(styleOptionEntity.getItemId ())) {
			keyOfMap = CACHE_QUALITY_VALUE_MAP_37;
		}
		qualityValueMap = 	(Map<String, List<Order>>) CacheUtils.get(keyOfMap);
		List<Order> returnOrders = qualityValueMap.get(styleOptionEntity.getStyleBarCode());
		Order returnOrder = returnOrders.get(0);
		for (StyleOptionEntity sEntity:returnOrder.getStyleOpList()) {
			if ((sEntity.getItemCode()+"-"+sEntity.getItemValue()).equals(styleOptionEntity.getItemCode()+"-"+styleOptionEntity.getItemValue())) {
				sEntity.setQcCheck(styleOptionEntity.getQcCheck());
			}
		}
		qualityValueMap.put(styleOptionEntity.getStyleBarCode(), Lists.newArrayList(returnOrder));
		CacheUtils.put(keyOfMap, qualityValueMap);
    }
    
    /**
     *保存订单质检状态信息
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("customization:quality:edit")
    @RequestMapping(value = "saveOrderStatus")
    @ResponseBody
    public String saveOrderStatus(StyleOptionEntity styleOptionEntity, HttpServletResponse response) throws ResourceException {
        // 保存数据
        customizationQualityService.saveOrderStatus(styleOptionEntity);
        // 保存成功返回提示信息
        return renderString(response, "");


    }
    
    /**
     *保存订单质检状态信息
     *
     * @return
     * @throws ParseException
     * @throws ResourceException
     */
    @RequiresPermissions("customization:quality:edit")
    @RequestMapping(value = "saveProItem")
    @ResponseBody
    public String saveProItem(StyleOptionEntity styleOptionEntity, HttpServletResponse response) throws ResourceException {
        // 保存数据
        customizationQualityService.saveProItem(styleOptionEntity);
        // 保存成功返回提示信息
        return renderString(response, "");


    }
    
	/**
	 *查询订单是否存在
	 * 
	 * @return
	 * 
	 * 
	 */
	@RequiresPermissions("customization:quality:view")
	@RequestMapping(value = "checkExist")
	@ResponseBody
	public String checkExist(CustomizationQualityEntity customizationQualityEntity, HttpServletRequest request, HttpServletResponse response,
			Model model) {
			Map<Object, Object> listMap = new HashMap<Object, Object> ();
			if ("1".equals (customizationQualityEntity.getWriteKbn ())) {
				Order order = customizationQualityService.getOrderByNo(customizationQualityEntity.getOrderCd());
				if (order!=null) {
					return renderString(response, true);
				}
			} else if ("2".equals (customizationQualityEntity.getWriteKbn ())) {
				String strOrderNo = customizationQualityService.selectBarCode(customizationQualityEntity.getBarCode ());
				if (strOrderNo!=null&&strOrderNo!="") {
					listMap.put ("strOrderNo",strOrderNo);
					listMap.put ("flg","true");
					return renderString(response, listMap);
				} else {
					listMap.put ("flg","false");
					return renderString(response, listMap);
				}
			} else {
				return renderString(response, false);
			}
			return renderString(response, false);
	}
}
